#!/bin/bash

# 服务名称（用于日志和PID管理）
SERVICE_NAME="elm-server"

# JDK 17 路径（如果未全局配置）
#export JAVA_HOME=/usr/local/jdk-17.0.x  # 替换为你的 JDK 17 路径
#export PATH=$JAVA_HOME/bin:$PATH

# Spring Boot JAR 文件路径
JAR_FILE="/data/cgk/elm-server.jar"

# 默认激活的profile（可通过命令行参数覆盖）
DEFAULT_PROFILE="prod"

# JVM 参数（优化内存配置：2g 初始堆，3g 最大堆）
JVM_OPTS="
  -Xms2g -Xmx3g
  -XX:+UseG1GC
  -XX:MaxGCPauseMillis=200
  -XX:+HeapDumpOnOutOfMemoryError
  -XX:HeapDumpPath=/data/log/${SERVICE_NAME}-heapdump.hprof
  -XX:+ExitOnOutOfMemoryError
  -Xlog:gc*:file=/data/log/${SERVICE_NAME}-gc.log:time,uptime,level,tags:filecount=5,filesize=10M
"

# 日志文件路径
LOG_FILE="/data/log/${SERVICE_NAME}.log"

# PID 文件路径（用于管理进程）
PID_FILE="/data/run/${SERVICE_NAME}.pid"

# 创建必要的目录
mkdir -p /data/log /data/run

# 检查JAR文件是否存在
check_jar() {
    if [ ! -f "$JAR_FILE" ]; then
        echo "Error: JAR file not found at $JAR_FILE"
        exit 1
    fi
}

# 检查Java是否可用
check_java() {
    if ! command -v java &> /dev/null; then
        echo "Error: Java is not installed or not in PATH"
        exit 1
    fi
}

# 检查进程是否正在运行
is_running() {
    if [ -f "$PID_FILE" ]; then
        if ps -p $(cat "$PID_FILE") > /dev/null 2>&1; then
            return 0
        else
            # 清理无效的PID文件
            rm -f "$PID_FILE"
        fi
    fi
    return 1
}

# 启动服务
start() {
    check_jar
    check_java

    if is_running; then
        echo "Service $SERVICE_NAME is already running (PID: $(cat $PID_FILE))."
        exit 1
    fi

    # 获取profile参数，如果没有则使用默认
    local profile=${2:-$DEFAULT_PROFILE}

    echo "Starting $SERVICE_NAME with profile: $profile..."
    nohup java $JVM_OPTS -jar $JAR_FILE --spring.profiles.active=$profile >> $LOG_FILE 2>&1 &

    local pid=$!
    echo $pid > $PID_FILE

    # 等待服务启动完成
    sleep 5
    if is_running; then
        echo "Service $SERVICE_NAME started successfully (PID: $pid)."
    else
        echo "Error: Failed to start $SERVICE_NAME"
        rm -f "$PID_FILE"
        exit 1
    fi
}

# 停止服务
stop() {
    if ! is_running; then
        echo "Service $SERVICE_NAME is not running."
        return 0
    fi

    echo "Stopping $SERVICE_NAME (PID: $(cat $PID_FILE))..."
    kill $(cat "$PID_FILE")

    # 等待进程停止
    local wait_time=0
    while is_running && [ $wait_time -lt 30 ]; do
        sleep 1
        wait_time=$((wait_time+1))
    done

    if is_running; then
        echo "Warning: Service did not stop gracefully, forcing kill..."
        kill -9 $(cat "$PID_FILE")
        sleep 1
    fi

    rm -f "$PID_FILE"
    echo "Service $SERVICE_NAME stopped."
}

# 重启服务
restart() {
    stop
    sleep 3
    start "$@"
}

# 查看服务状态
status() {
    if is_running; then
        echo "Service $SERVICE_NAME is running (PID: $(cat $PID_FILE))."
        return 0
    else
        echo "Service $SERVICE_NAME is not running."
        return 1
    fi
}

# 查看日志
tail_log() {
    if [ -f "$LOG_FILE" ]; then
        tail -f "$LOG_FILE"
    else
        echo "Log file not found: $LOG_FILE"
        exit 1
    fi
}

# 处理命令行参数
case "$1" in
    start)
        start "$@"
        ;;
    stop)
        stop
        ;;
    restart)
        restart "$@"
        ;;
    status)
        status
        ;;
    log)
        tail_log
        ;;
    *)
        echo "Usage: $0 {start [profile]|stop|restart [profile]|status|log}"
        echo "Example:"
        echo "  $0 start dev      # 使用dev profile启动服务"
        echo "  $0 restart prod   # 使用prod profile重启服务"
        echo "  $0 stop           # 停止服务"
        echo "  $0 status         # 查看服务状态"
        echo "  $0 log            # 查看实时日志"
        exit 1
esac

exit 0